﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SangsTools;
using UnityEngine.AddressableAssets;
using LitJson;
using UnityEngine;

namespace Item
{
    public class ItemDataMgr : SingletonScript<ItemDataMgr>
    {
        private const string TBLPath = "Addressable/TBL", AddressableName = "ItemData";
        private Dictionary<string, STItemData> dictItemData;
        public IEnumerable<STItemData> AllItemData => dictItemData.Values;

        public ItemDataMgr()
        {
            dictItemData = new Dictionary<string, STItemData>();
        }

        public STItemData? this[string tag]
        {
            get => dictItemData.ContainsKey(tag) ? (STItemData?)dictItemData[tag] : null;
            set
            {
                if (value != null && value?.strItemTag != null)
                {
                    if (dictItemData.ContainsKey(tag))
                        dictItemData[tag] = value.Value;
                    else
                        dictItemData.Add(tag, value.Value);
                }
            }
        }

        public async Task LoadTBLDataAsync()
        {
            TextAsset textAsset = await Addressables.LoadAssetAsync<TextAsset>(AddressableName).Task;
            if (textAsset != null)
            {
                try
                {
                    dictItemData = new Dictionary<string, STItemData>();
                    JsonData json = JsonMapper.ToObject(textAsset.text);
                    foreach (var item in (json as IDictionary).Keys)
                    {
                        dictItemData.Add(item.ToString(), new STItemData(json[item.ToString()]));
                    }
                }
                catch(Exception e)
                {
                    throw new Exception("-道具-信息表数据异常 --- " + e.ToString());
                }
            }
            else
                throw new Exception("-道具-信息表加载失败");
        }

#if UNITY_EDITOR
        public void SaveTBLData()
        {
            JsonData jsonData = new JsonData();
            foreach (var item in dictItemData)
            {
                jsonData[item.Key] = item.Value.json;
            }
            string json = jsonData.ToJson();

            //Debug.Log(json.ToUTF8());
            MyJsonTools.SaveJsonFile(json.ToUTF8(), TBLPath, AddressableName);
        }
#endif

    }
}
